<template>
  <el-container class="water-monitor-layout" fullscreen>
    <!-- 左侧：水表树形选择（带多选） -->
    <el-aside width="280px" class="aside-panel">
      <div class="aside-header">
        <el-icon class="header-icon"><LocationFilled /></el-icon>
        <span class="header-title">选中待查询的水表</span>
      </div>
      <el-tree
          ref="areaMeterTree"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="false"
          :check-on-click-node="true"
          show-checkbox
          node-key="id"
          :filter-node-method="filterTreeNode"
          @check-change="handleCheckChange"
          class="tree-container"
          v-loading="treeLoading"
          loading-text="加载区域与水表数据中..."
      >
        <template #default="{ node }">
          <div class="node-content">
            <!-- 区域节点图标 -->
            <el-icon v-if="node.data.type === 'area'" class="node-icon area-icon">
              <OfficeBuilding />
            </el-icon>
            <!-- 水表节点图标 -->
            <el-icon v-else-if="node.data.type === 'meter'" class="node-icon meter-icon">
              <WaterFilled />
            </el-icon>
            <span class="node-label">{{ node.label }}</span>
          </div>
        </template>
      </el-tree>
    </el-aside>

    <!-- 右侧：筛选条件 + 表格 -->
    <el-main class="main-content">
      <div class="filter-bar">
        <!-- 日期范围选择 -->
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="date-picker"
        />

        <!-- 今日用水量范围（对应数据库 todayUsage） -->
        <div class="flow-range">
          <span class="range-label">今日用水量范围：</span>
          <el-input-number
              v-model="flowRange.min"
              :min="0"
              :step="0.1"
              placeholder="最小值"
              class="range-input"
              size="small"
          />
          <span class="range-separator">-</span>
          <el-input-number
              v-model="flowRange.max"
              :min="flowRange.min || 0"
              :step="0.1"
              placeholder="最大值"
              class="range-input"
              size="small"
          />
        </div>

        <!-- 其他参数（可根据需求调整/简化） -->
        <div class="other-params">
          <el-select
              v-model="checkType"
              placeholder="选择类型"
              size="small"
              class="param-select"
          >
            <el-option label="瞬时" value="instant" />
            <el-option label="累计" value="cumulative" />
          </el-select>
          <el-input-number
              v-model="step"
              label="步长"
              :min="1"
              :step="1"
              value="1"
              size="small"
              class="param-input"
          />
          <el-input-number
              v-model="threshold"
              label="阈值"
              :min="0"
              :step="1"
              value="10"
              size="small"
              class="param-input"
          />
        </div>

        <!-- 查询按钮 -->
        <el-button type="primary" @click="handleQuery" class="query-btn">
          <el-icon><Search /></el-icon>查询
        </el-button>

        <!-- 平均合格率显示 -->
        <div class="average-rate" v-if="averageRate !== null">
          平均合格率：<span class="rate-value">{{ averageRate.toFixed(2) }}%</span>
        </div>
      </div>

      <!-- 表格展示 -->
      <div class="table-container">
        <el-table
            :data="tableData"
            border
            v-loading="tableLoading"
            loading-text="加载数据中..."
            style="width: 100%;"
        >
          <el-table-column
              prop="meterName"
              label="水表编号"
              align="center"
              min-width="150"
          />
          <el-table-column
              prop="checkType"
              label="检测类型"
              align="center"
              min-width="100"
          />
          <el-table-column
              prop="checkTime"
              label="检测时间"
              align="center"
              min-width="150"
          />
          <el-table-column
              prop="todayUsage"
              label="今日用水量"
              align="center"
              min-width="120"
          />
          <el-table-column
              prop="qualifiedCount"
              label="是否合格"
              align="center"
              min-width="100"
              :formatter="formatQualifiedCount"
          />
          <el-table-column
              prop="totalCount"
              label="总检测数量"
              align="center"
              min-width="100"
          />
          <el-table-column
              prop="qualifiedRate"
              label="合格率"
              align="center"
              min-width="100"
          >
            <template #default="scope">
              <span :class="scope.row.qualifiedRate >= 90 ? 'high-rate' : 'low-rate'">
                {{ scope.row.qualifiedRate.toFixed(2) }}%
              </span>
            </template>
          </el-table-column>
        </el-table>
        <div class="empty-tip" v-if="!tableLoading && tableData.length === 0">
          <el-icon class="empty-icon"><InfoFilled /></el-icon>
          <p class="empty-text">暂无数据，请选择水表并设置查询条件</p>
        </div>
      </div>
    </el-main>
  </el-container>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElButton, ElDatePicker, ElTree, ElIcon, ElTable, ElTableColumn, ElInputNumber, ElSelect, ElOption } from 'element-plus'
// 引入图标
import { LocationFilled, OfficeBuilding, InfoFilled, Search} from '@element-plus/icons-vue'
// 引入API（需确保后端接口返回 `meterName`、`todayUsage`、`recordTime`/`analyseDate` 等字段）
import { listArea } from '@/api/water/area'
import { listElement } from '@/api/water/element'
import { listMeterAnalyse } from '@/api/water/meterAnalyse'
// 时间工具
import dayjs from 'dayjs'

// ========== 响应式数据 ==========
// 树形结构相关
const treeData = ref([])
const treeProps = ref({ children: 'children', label: 'label' })
const checkedMeters = ref([]) // 选中的水表ID集合
const treeLoading = ref(false)

// 筛选条件
const dateRange = ref([])
const flowRange = ref({ min: null, max: null })
const checkType = ref('instant')
const step = ref(1)
const threshold = ref(10)

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)
const averageRate = ref(null) // 平均合格率


// ========== 页面初始化 ==========
onMounted(() => {
  initAreaMeterTree()
  // 默认选中“当天”日期
  const today = dayjs().format('YYYY-MM-DD')
  dateRange.value = [today, today]
})


// ========== 树形结构逻辑 ==========
/** 初始化区域-水表树形数据 */
const initAreaMeterTree = async () => {
  treeLoading.value = true
  try {
    // 获取区域列表
    const areaRes = await listArea({ pageNum: 1, pageSize: 1000 })
    if (areaRes.code !== 200) throw new Error('获取区域数据失败')
    // 获取水表列表
    const meterRes = await listElement({ pageNum: 1, pageSize: 1000 })
    if (meterRes.code !== 200) throw new Error('获取水表数据失败')

    // 构建区域树形 + 分配水表到区域
    const areaTree = buildAreaTree(areaRes.rows)
    const finalTree = assignMetersToArea(areaTree, meterRes.rows)
    treeData.value = finalTree
  } catch (err) {
    ElMessage.error(err.message || '初始化数据失败')
    console.error('树形数据初始化错误：', err)
  } finally {
    treeLoading.value = false
  }
}

/** 构建区域树形结构 */
const buildAreaTree = (areas) => {
  const areaMap = new Map()
  const rootAreas = []
  areas.forEach(area => {
    areaMap.set(area.id, {
      ...area,
      type: 'area',
      label: area.areaName,
      children: []
    })
  })
  areaMap.forEach(area => {
    const parentId = area.parentAreaId
    if (!parentId || parentId === 0 || !areaMap.has(parentId)) {
      rootAreas.push(area)
    } else {
      areaMap.get(parentId).children.push(area)
    }
  })
  return rootAreas
}

/** 分配水表到对应区域 */
const assignMetersToArea = (areaTree, meters) => {
  const [meterWithArea, meterWithoutArea] = meters.reduce((acc, meter) => {
    const hasFirstArea = !['', null, undefined].includes(meter.firstAreaId)
    const hasNegativeArea = !['', null, undefined].includes(meter.negativeAreaId)
    if (hasFirstArea || hasNegativeArea) acc[0].push(meter)
    else acc[1].push(meter)
    return acc
  }, [[], []])

  const traverse = (nodes) => {
    nodes.forEach(node => {
      if (node.type === 'area') {
        const matchedMeters = meterWithArea.filter(meter =>
            meter.firstAreaId === node.id || meter.negativeAreaId === node.id
        ).map(meter => ({
          ...meter,
          type: 'meter',
          label: meter.negativeAreaId === node.id
              ? `${meter.elemName}-反向表`
              : meter.elemName,
          children: null
        }))
        node.children = [...node.children, ...matchedMeters]
        if (node.children && node.children.length > 0) traverse(node.children)
      }
    })
  }
  traverse(areaTree)

  // 处理无区域的水表，归到“其他”分类
  if (meterWithoutArea.length > 0) {
    areaTree.push({
      id: 'other_area_placeholder',
      type: 'area',
      label: '其他（无区域的水表）',
      children: meterWithoutArea.map(meter => ({
        ...meter,
        type: 'meter',
        label: meter.elemName,
        children: null
      }))
    })
  }
  return areaTree
}

/** 树形节点选择变化：维护选中的水表ID */
const handleCheckChange = (data, checked, indeterminate) => {
  if (data.type === 'meter') {
    // 水表节点：直接增删ID
    checked ?
        !checkedMeters.value.includes(data.id) && checkedMeters.value.push(data.id) :
        checkedMeters.value.splice(checkedMeters.value.indexOf(data.id), 1)
  } else if (data.type === 'area') {
    // 区域节点：递归处理子级水表ID
    const meterIds = (data.children || []).filter(c => c.type === 'meter').map(c => c.id)
    checked ?
        meterIds.forEach(id => !checkedMeters.value.includes(id) && checkedMeters.value.push(id)) :
        meterIds.forEach(id => checkedMeters.value.splice(checkedMeters.value.indexOf(id), 1))
  }
}


// ========== 查询与数据处理逻辑 ==========
/** 处理查询：前端统计合格率 */
const handleQuery = async () => {
  // 校验必填条件
  if (checkedMeters.value.length === 0) return ElMessage.warning('请至少选择一个水表')
  if (!dateRange.value?.length || !dateRange.value[0] || !dateRange.value[1])
    return ElMessage.warning('请选择日期范围')
  if (flowRange.value.min === null || flowRange.value.max === null)
    return ElMessage.warning('请设置完整的流量范围')
  if (flowRange.value.min >= flowRange.value.max)
    return ElMessage.warning('流量最小值不能大于等于最大值')

  tableLoading.value = true
  try {
    // 调用后端接口，获取选中水表的 todayUsage 等数据
    const res = await listMeterAnalyse({
      meterIds: checkedMeters.value.join(','),
      startTime: dateRange.value[0],
      endTime: dateRange.value[1]
    })
    if (res.code !== 200) throw new Error('获取水表数据失败')

    const meterDataList = res.rows || []
    const totalCount = checkedMeters.value.length // 总检测数量（选中的水表数）
    let qualifiedCount = 0 // 合格数量（todayUsage 在范围内的水表数）

    // 前端处理：统计合格数 + 构造表格数据
    tableData.value = meterDataList.map(item => {
      const isQualified = item.todayUsage !== null &&
          item.todayUsage >= flowRange.value.min &&
          item.todayUsage <= flowRange.value.max
      if (isQualified) qualifiedCount++
      return {
        meterName: item.meterName,
        checkType: checkType.value,
        checkTime: item.recordTime || item.analyseDate || new Date(), // 取时间字段
        todayUsage: item.todayUsage,
        qualifiedCount: isQualified ? 1 : 0, // 该水表是否合格（1/0）
        totalCount, // 总检测数量
        qualifiedRate: isQualified ? 100 : 0 // 该水表的合格率
      }
    })

    // 计算平均合格率
    calculateAverageRate()
  } catch (err) {
    ElMessage.error(err.message || '查询失败，请重试')
    console.error('查询错误：', err)
  } finally {
    tableLoading.value = false
  }
}

/** 计算平均合格率：合格水表数 / 总水表数 * 100 */
const calculateAverageRate = () => {
  if (tableData.value.length === 0) {
    averageRate.value = null
    return
  }
  const qualifiedMeterCount = tableData.value.filter(item => item.qualifiedCount === 1).length
  const totalMeterCount = tableData.value.length
  averageRate.value = totalMeterCount > 0
      ? (qualifiedMeterCount / totalMeterCount) * 100
      : 0
}

/** 格式化“是否合格”为文字（1→是，0→否） */
const formatQualifiedCount = (row) => row.qualifiedCount === 1 ? '是' : '否'


// ========== 树形过滤逻辑 ==========
const filterTreeNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}
</script>
<style scoped>
.water-monitor-layout {
  display: flex;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.aside-panel {
  height: 100%;
  background-color: #f8f9fa;
  border-right: 1px solid #e9ecef;
}

.aside-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  margin-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
}

.header-icon {
  color: #409eff;
  font-size: 18px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.tree-container {
  height: calc(100% - 60px);
  overflow-y: auto;
  padding: 0 16px;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-icon {
  font-size: 14px;
}

.area-icon {
  color: #409eff;
}

.meter-icon {
  color: #67c23a;
}

.main-content {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.date-picker {
  width: 300px;
}

.flow-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-label {
  color: #606266;
  white-space: nowrap;
}

.range-input {
  width: 120px;
}

.range-separator {
  color: #606266;
}

.other-params {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-left: auto;
}

.param-select {
  width: 120px;
}

.param-input {
  width: 100px;
}

.query-btn {
  margin-left: 16px;
}

.average-rate {
  margin-left: 16px;
  color: #606266;
  font-weight: 500;
}

.rate-value {
  color: #409eff;
  font-weight: bold;
}

.table-container {
  flex: 1;
  position: relative;
  overflow: auto;
  border: 1px solid #e9ecef;
  border-radius: 4px;
}

.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.high-rate {
  color: #67c23a;
  font-weight: 500;
}

.low-rate {
  color: #f56c6c;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 1400px) {
  .other-params {
    margin-left: 0;
    margin-top: 12px;
    width: 100%;
  }
  .average-rate {
    margin-left: 0;
    margin-top: 12px;
  }
}

@media (max-width: 768px) {
  .date-picker {
    width: 100%;
  }
  .flow-range {
    width: 100%;
    margin-top: 12px;
  }
  .range-input {
    flex: 1;
  }
}
</style>